﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.Common.Component.OAuth.Weixing;
using RiderShop.Mobile.Modle;
using Kevin.Shop.Business.Core.Components.Responser;
using RiderShop.Mobile.Common.Helper;
using RiderShop.Mobile.Modle.MyAccount;

namespace RiderShop.Mobile.Controllers
{
    public partial class CustomerController : ThemeController
    {
        public ActionResult Login(string returnUrl)
        {
            if (WebClientContext.Current.IsAuthenticated)
            {
                if (String.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToAction("Index", "Home");
                }
                {
                    return Redirect(returnUrl);
                }
            }

            //尝试微信登录
            if (Request.UserAgent.Contains("MicroMessenger"))
            {
                if (!string.IsNullOrEmpty(WebClientContext.Current.OpenId) && WeixingOAuth.LoginByThirdId(WebClientContext.Current.OpenId))
                {
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    {
                        return Redirect(returnUrl);
                    }
                }
            }

            return View(WebClientContext.Current.SiteTheme, "Customer", "Login", WebClientContext.Current.CacheKeyDefaultMasterPage, new CustomerModel());
            //return View(new CustomerModel());
        }


        [HttpPost]
        public ActionResult Login(string userName, string passWord, string returnUrl)
        {

            var model = new CustomerModel();
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passWord))
            {
                model.Result = new ServiceResponser()
                {
                    Status = false,
                    ErrorMessage = "账号名和密码不能为空"
                };
                return View(model);
            }
            model.Login(userName, passWord);
            if (model.Result == null || !model.Result.Status)
            {
                model.ReturnUrl = returnUrl;
                return View(model);
            }
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, true);
            KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
            WebClientContext.Current.GetCurrentUser();
            FormsAuthentication.RedirectFromLoginPage(userName, true);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult Register(UserBasicInfo user)
        {
            string returnUrl = Request.Form["returnUrl"];

            if (WebClientContext.Current.IsAuthenticated)
            {
                if (String.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToAction("Index", "Home");
                }
                {
                    return Redirect(returnUrl);
                }
            }

            var model = new CustomerModel();


            if (string.IsNullOrEmpty(user.UserName))
            {
                //简化注册流程。省略用户名
                user.UserName = user.Email;
                user.RealName = user.CellPhone;


                //model.Result = new ServiceResponser()
                //{
                //    Status = false,
                //    ErrorMessage = "账号不能为空"
                //};
                //return View(model);
            }

            if (user == null || string.IsNullOrEmpty(user.UserName))
            {
                if (!string.IsNullOrEmpty(user.ThirdUserId))
                {
                    model.CurrentUser = new UserBasicInfo();
                    model.CurrentUser.ThirdUserId = user.ThirdUserId;
                }
                return View(WebClientContext.Current.SiteTheme, "Customer", "Register", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            model.Register(user);
            if (!model.Result.Status)
            {
                model.ReturnUrl = returnUrl;

                return View(WebClientContext.Current.SiteTheme, "Customer", "Register", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
            KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
            WebClientContext.Current.GetCurrentUser();

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }


        public ActionResult PhoneRegister(UserBasicInfo user)
        {
            string returnUrl = Request.Form["returnUrl"];

            if (WebClientContext.Current.IsAuthenticated)
            {
                if (String.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToAction("Index", "Home");
                }
                {
                    return Redirect(returnUrl);
                }
            }

            var model = new CustomerModel();


            if (user == null || string.IsNullOrEmpty(user.CellPhone))
            {
                return View(WebClientContext.Current.SiteTheme, "Customer", "PhoneRegister", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            model.RegisterUserByCellPhone(user.CellPhone, user.Password, user.PasswordAnswer, "MobileWebsite");
            if (!model.Result.Status)
            {
                model.ReturnUrl = returnUrl;

                return View(WebClientContext.Current.SiteTheme, "Customer", "PhoneRegister", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            user = CacheUsers.Get(int.Parse(model.Result.Tag), true);

            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
            KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
            WebClientContext.Current.GetCurrentUser();

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            KevinCookieManager.Remove("openid");
            return RedirectToAction("Index", "Home");
        }

        public ActionResult WeixinLogin(string returnUrl)
        {
            var result = WeixingOAuth.OAuth();
            if (result.Status)
            {
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            //微信认证成功，但是用户未绑定
            else if (result.WeixinUserInfo != null)
            {
                KevinCookieManager.Set("winxinInfo", Kevin.Comm.Utility.Serializer.ConvertObjectToJson(result.WeixinUserInfo));
                // return Redirect(string.Format("~/Customer/BindWeixinAuth?openid={0}&returnUrl={1}", result.WeixinUserInfo.openid, returnUrl));
                return RedirectToAction("BindWeixinAuth", "Customer", new { returnUrl = returnUrl, openid = result.WeixinUserInfo.openid });
            }

            return RedirectToAction("Login", "Customer");
        }

        public ActionResult BindWeixinAuth()
        {
            CustomerModel model = new CustomerModel();
            model.OpenId = Request.QueryString["openid"];
            if (WebClientContext.Current.IsAuthenticated)
            {
                var user = WebClientContext.Current.GetCurrentUser();
                if (!string.IsNullOrEmpty(user.ThirdUserId))
                {
                    model.Result = new ServiceResponser(false, "你已经绑定微信，如需更新微信账户，请再次点击绑定");
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindWeixinAuth", "_MobileLayout", model);
                }
            }


            return View(WebClientContext.Current.SiteTheme, "Customer", "BindWeixinAuth", "_MobileLayout", model);
        }

        [HttpPost]
        public ActionResult BindWeixinAuth(string userName, string passWord, string returnUrl, string openid)
        {
            CustomerModel model = new CustomerModel();
            model.OpenId = openid;
            if (!WebClientContext.Current.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(passWord))
                {
                    model.Result = new Kevin.Shop.Business.Core.Components.Responser.ServiceResponser()
                    {
                        Status = false,
                        ErrorMessage = "用户名和密码不能为空"
                    };
                }
                model.Login(userName, passWord);

                //登录失败
                if (model.Result == null || !model.Result.Status)
                {
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindWeixinAuth", "_MobileLayout", model);
                }
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, true);
                KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
                FormsAuthentication.RedirectFromLoginPage(userName, true);

            }
            else
            {
                userName = WebClientContext.Current.UserName;
            }

            if (string.IsNullOrEmpty(openid))
            {
                model.Result = new ServiceResponser(false, "请在微信中登录");
                return View(WebClientContext.Current.SiteTheme, "Customer", "BindWeixinAuth", "_MobileLayout", model);
            }

            //微信绑定成功，缓存openid
            WebClientContext.Current.OpenId = openid;

            if (!string.IsNullOrEmpty(KevinCookieManager.Get("winxinInfo")))
            {
                var weixinUserInfo = Kevin.Comm.Utility.Serializer.ConvertJsonToObject<RiderShop.Mobile.Common.ThirdEntity.WinXinUserInfo>(KevinCookieManager.Get("winxinInfo"));

                if (weixinUserInfo != null && !string.IsNullOrEmpty(weixinUserInfo.openid))
                {
                    KevinCookieManager.Remove("winxinInfo");
                    model.BindUserInfoByWeixin(userName, weixinUserInfo);
                }
                else
                {
                    model.BindUserInfoByWeixin(userName, openid);
                }
            }
            return Redirect("~/MyAccount/Home");

        }

        public ActionResult WeixinRegister()
        {
            CustomerModel model = new CustomerModel();

            if (!string.IsNullOrEmpty(KevinCookieManager.Get("winxinInfo")))
            {
                var weixinUserInfo = Kevin.Comm.Utility.Serializer.ConvertJsonToObject<RiderShop.Mobile.Common.ThirdEntity.WinXinUserInfo>(KevinCookieManager.Get("winxinInfo"));

                if (weixinUserInfo != null && !string.IsNullOrEmpty(weixinUserInfo.openid))
                {
                    KevinCookieManager.Remove("winxinInfo");
                    model.WeixinRegister(weixinUserInfo);

                    WeixingOAuth.LoginByThirdId(weixinUserInfo.openid);


                    return Redirect("~/MyAccount/Home");
                }
            }


            return RedirectToAction("Login", "Customer");
        }

        public ActionResult ThirdRegister(string userName, string tel, string openid, string returnUrl)
        {
            if (!WeixingOAuth.LoginByThirdId(openid))
            {
                var model = new CustomerModel();
                UserBasicInfo user = new UserBasicInfo()
                {
                    ThirdUserId = "weixing_" + openid,
                    UserName = "weixing_" + System.DateTime.Now.ToString("yyMMddhhmmssfff"),
                    RealName = userName,
                    TelPhone = tel,
                    CellPhone = tel,
                    MSN = "weixinfirstlogin", //作为微信注册标记字段，用户绑定手机号设置密码后清空
                    Password = "!@#$%^&*()",
                    Email = openid + "@qq.com",
                    EnableEmail = false
                };

                model.Register(user);
                if (model.Result.Status)
                {
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, true);
                    KevinCookieManager.Set(authCookie.Name, authCookie.Value, 10000);
                    WebClientContext.Current.GetCurrentUser();
                    WebClientContext.Current.OpenId = openid;
                }
            }
            return Redirect(returnUrl);

        }
    }
}
